package cn.jingyuan.owl.web.core;

import cn.jingyuan.owl.model.core.Result;
import cn.jingyuan.owl.model.error.ErrorCode;

public class ResultUtils {

    private ResultUtils() {}

    //region Result

    public static <D> Result<D> ok() {
        return new <D>Result<D>()
            .setCode(ExCode.SUCCESS.getCode())
            .setCodeMsg(ExCode.SUCCESS.getCodeMsg());
    }

    public static <D> Result<D> ok(D data) {
        return new <D>Result<D>()
            .setCode(ExCode.SUCCESS.getCode())
            .setCodeMsg(ExCode.SUCCESS.getCodeMsg())
            .setData(data);
    }

    public static <D> Result<D> failure() {
        return new <D>Result<D>()
            .setCode(ExCode.FAILURE.getCode())
            .setCodeMsg(ExCode.FAILURE.getCodeMsg());
    }

    public static <D> Result<D> warning() {
        return new <D>Result<D>()
            .setCode(ExCode.WARNING.getCode())
            .setCodeMsg(ExCode.WARNING.getCodeMsg());
    }

    public static <D> Result<D> warning(String msg) {
        return new <D>Result<D>()
            .setCode(ExCode.WARNING.getCode())
            .setCodeMsg(msg);
    }

    public static <D> Result<D> instance(ErrorCode exCode) {
        return new <D>Result<D>()
            .setCode(exCode.getCode())
            .setCodeMsg(exCode.getCodeMsg());
    }

    //endregion

    //region 工具类

    public static boolean isSuccess(Result<?> result) {
        nonNull(result);

        return ExCodeUtils.isSuccess(result.getCode());
    }

    public static boolean isError(Result<?> result) {
        nonNull(result);

        return ExCodeUtils.isError(result.getCode());
    }

    public static boolean matchFailure(Result<?> result) {
        nonNull(result);

        return ExCodeUtils.matchFailure(result.getCode());
    }

    public static boolean isNull(Result<?> result) {
        return null == result;
    }

    public static boolean isNotNull(Result<?> result) {
        return null != result;
    }

    public static void nonNull(Result<?> result) {
        if (null == result) {
            throw new NullPointerException("result is null");
        }
    }

    public static void nonNull(Result<?> result, RuntimeException e) {
        if (null == result) {
            throw e;
        }
    }

    //endregion

}
